<?php
/**
 * @author fyl
 * Date: 16-3-29 下午2:59
 */
class ApiUserService extends BaseService
{
    private static $self           =   NULL;
    private $mUser                 =   NULL;
    private $mUserMessage          =   NULL;
    private $mUserAward            =   NULL;
    private $mUserTicket           =   NULL;
    private $mDealDeposit          =   NULL;
    private $mUserFund             =   NULL;
    private $mUserLock             =   NULL;
    private $mRefundPlan           =   NULL;
    private $mBankCard             =   NULL;
    private $mExperRecord          =   NULL;
    private $mInviteCode           =   NULL;
    private $mInvest               =   NULL;
    private $mNew                  =   NULL;
    private $mAccrualDay           =   NULL;
    private $mVersion              =   NULL;


    static public function instance()
    {
        if (self::$self == NULL) {
            self::$self = new self;
        }
        return self::$self;
    }


    public function __construct()
    {

        $this->mUser                   =   new Involved_UserModel();
        $this->mUserMessage            =   new Involved_UserMessageModel();
        $this->mUserTicket             =   new Involved_UserTicketModel();
        $this->mUserAward              =   new Involved_UserAwardModel();
        $this->mDealDeposit            =   new Involved_DealDepositModel();
        $this->mUserFund               =   new Involved_UserFundModel();
        $this->mUserLock               =   new Involved_UserLockModel();
        $this->mRefundPlan             =   new Involved_RefundPlanModel();
        $this->mBankCard               =   new Involved_BankCardModel();
        $this->mExperRecord            =   new Involved_ExperRecordModel();
        $this->mInviteCode             =   new Involved_InviteCodeModel();
        $this->mInvest                 =   new Involved_InvestModel();
        $this->mNew                    =   new Involved_NewsModel();
        $this->mAccrualDay             =   new Involved_AccrualDayModel();
        $this->mVersion                =   new Involved_VersionModel();


    }


    /**
     * 参数验证
     * @param $obj
     * @param $arr
     * @author alice
     * @date 2016-1-13
     * @return bool
     * @return bool
     */
    public function  checkProperties($obj, $arr)
    {
        if (empty($arr)) return true;
        $obj = (array)$obj;

        foreach ($arr as $v) {
            if (is_null($obj[$v])) {
                return false;
            }
        }
        return true;
    }


    /**
     *判断处理
     *xf
     **/
    public function Userlogin($paramObj)
    {
        //php判断是否为空
        if (empty($paramObj->phones) || empty($paramObj->pwd)) {
            throw new Exception("参数不足", ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        if (!preg_match("/^1[34578]{1}\d{9}$/", $paramObj->phones)) {
            throw new Exception("请输入正确的手机号", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }
//        if (!preg_match("/(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,16}$/", $paramObj->pwd)) {
//            throw new Exception("6-16个字符，由字母+数字和符号两种以上组合", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
//        }
        //php是否存在
        $data = $this->mUser->UserFirphone($paramObj->phones);
        if (empty($data->user_id)) {
            throw new Exception("用户不存在", ProfessionErrorCodeEnum::ERROR_ACCOUNT_NOT_EXIST);
        }
        //是不是后台禁止登陆
        if ($data->is_locked == '1') {
            throw new Exception("对不起，您的账号已被限制，请联系客服", ProfessionErrorCodeEnum::ERROR_ACCOUNT_UNAVAILABLE);
        }
        $Lookcishu = $this->mUserLock->LockUsercishu($data->user_id);//获取登陆次数
        if (!empty($Lookcishu)) {
            $daes = strtotime(date('Ymd', $Lookcishu->lock_time)) + 86400;

            if (time() > $daes) {
                $LookUseraaaa = $this->mUserLock->delete(['user_id' => $Lookcishu->user_id]);
            }
        }
        $LookUsers = $this->mUserLock->LockUser($data->user_id);//获取人是不是本冻结
        if (!empty($LookUsers)) {//如果被冻结，看是否到解锁时间
            $LookUsersa = $this->mUserLock->LockUserfirst($data->user_id);
            if (time() < $LookUsersa->lock_time) {
                throw new Exception('对不起，您的账户已被锁定,请于' . date('H:i:s', $LookUsersa->lock_time) . '后尝试登录！', ProfessionErrorCodeEnum::ERROR_DB_DFALSE_LOCALK);
            } else {
                $LookUseraaaa = $this->mUserLock->delete(['user_id' => $data->user_id]);
            }
        }
        //加密判断
        $psswd = UserEnum::get(md5(md5($paramObj->pwd)), $data->salt);//加密方式
        if ($psswd == $data->password) {
            $date = $this->mUser->ApiUserFirphone($paramObj->phones);
            #存储SESSION
//                session_put(UserEnum::USER_INFO_USER_ID, $data->user_id);
//                session_put(UserEnum::USER_INFO_SESSION_KEY, $data);
//            $qwert=session_get(UserEnum::USER_INFO_SESSION_KEY);
//            return $qwert;
            $_SESSION[UserEnum::USER_INFO_USER_ID]=$data->user_id;
            $_SESSION[UserEnum::USER_INFO_SESSION_KEY]=$date;
            $qwert=$_SESSION[UserEnum::USER_INFO_SESSION_KEY];
            return $qwert;
        } else {
            $LookUser = $this->mUserLock->LockUserfirst($data->user_id);

            if (!empty($LookUser->number)) {
                $count = $LookUser->number;
                if ($count <= 4) {
                    $count--;
                    $logins = $count;
                    $array = array(
                        'number' => $logins,
                        'user_id' => $data->user_id,
                        'lock_time' => time(),
                        'ip' => $_SERVER['REMOTE_ADDR'],
                    );
//                    if ($count<1) {
//                        $LookUserd= $this->mUserLock->insert($array);
//                    }
                    if ($count >= 0 && $count <= 4) {
                        $LookUserd = $this->mUserLock->update($array, ['lock_id' => $LookUser->lock_id]);
                    }
                }
                if ($count == 0) {
                    $data4['number'] = $count;
                    $data4['user_id'] = $data->user_id;
                    $data4['lock_time'] = time() + 60 * 30;
                    $data4['ip'] = $_SERVER['REMOTE_ADDR'];
                    $LookUserd = $this->mUserLock->update($data4, ['lock_id' => $LookUser->lock_id]);
                    if (!empty($LookUserd)) {
                        throw new Exception("您已经连续5次输入错误密码，账户被锁定30分钟", ProfessionErrorCodeEnum::ERROR_DB_DFALSE_LOCALK_FIVEPWD);
                    }
                }
                throw new Exception('"密码有误，请重新输入,今天还剩' . $count . '次', ProfessionErrorCodeEnum::ERROR_DB_DFALSE_LOCALK_FIVEPWD);
            } else {
                $logins = 4;
                $array = array(
                    'number' => $logins,
                    'user_id' => $data->user_id,
                    'lock_time' => time(),
                    'ip' => $_SERVER['REMOTE_ADDR'],
                );
                $LookUserd = $this->mUserLock->insert($array);
            }
            if (empty($LookUser->number)) {
                throw new Exception(" 密码有误，请重新输入，今天还剩4次机会", ProfessionErrorCodeEnum::ERROR_DB_DFALSE_LOCALK_FIVEPWD);
            }

        }

    }





    /**
     * 注册
     * @param $paramObj
     * @throws Exception
     */
    public function DeposeRegister($paramObj)
    {

        #参数验证
        $check = $this->checkProperties($paramObj, ['mobile', 'password']);
        if (!$check) {
            throw new Exception($this->error_msg[ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST],
                ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }

        #密码验证
        if (!preg_match('/^(?![\d]+$)(?![a-zA-Z]+$)(?![!#$%^&*]+$)[\da-zA-Z!#$%^&*]{6,16}$/', $paramObj->password)) {
            throw new Exception("密码必须为6-6-16个字符，由字母+数字和符号两种以上组合", ProfessionErrorCodeEnum::ERROR_PASSWORD_FAILURE);
        }

        #手机号验证
        if (!preg_match('/^1[34578]\d{9}$/', $paramObj->mobile)) {
            throw new Exception("手机号码错误", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }

        #手机号是否已注册
        $mobile = $this->mUser->JsCheckMobile($paramObj->mobile);
        if ($mobile) {
            throw new Exception("手机号已注册", ProfessionErrorCodeEnum::ERROR_ACCOUNT_EXIST);
        }

        #邀请码是否存在
        if (!empty($paramObj->invite_code)) {
            $invite_code = $this->mUser->JsCheckCode($paramObj->invite_code);
            #邀请码验证
            if (!$invite_code) {
                throw new Exception("邀请码不存在", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
            }
        }


        $invite_code = $this->mInviteCode->insert(['invite_code' => 1]);

        $salt = rand(100000, 999999);
        #注册用户
        $aData = [
            'user_name' => 'GPW' . time(),
            'telephone' => $paramObj->mobile,
            'password' => UserEnum::get(md5(md5($paramObj->password)), $salt),
            'salt' => $salt,
            'invite_code' => $invite_code,
            'add_time' => time(),
        ];

        $user_id = $this->mUser->insert($aData);

        if ($user_id) {
            //注册送体验金
            DB::table('exper_amount')->insert(array(
                array('user_id' => $user_id, 'amount' => '666600', 'road' => 'REGISTER', 'status' => 'AVAILABLE', 'add_time' => time(), 'due_time' => time() + 86400 * 15),
            ));
            //注册送加息券
            DB::table('user_ticket')->insert(array(
                array('user_id' => $user_id, 'rate' => '100', 'restrict_item' => 'ALL', 'road' => 'REGISTER', 'status' => 'AVAILABLE', 'add_time' => time(), 'due_time' => time() + 86400 * 15),
            ));
            $this->mUserFund->insert(['user_id' => $user_id]);
            UserService::instance()->run($user_id);
            UserService::instance()->send(
            // 接收者ID
                $user_id,
                // 标题
                '恭喜您注册成功',
                // 内容
                '尊敬的用户，您已成功注册钢票网。6666元体验金和618元新手红包已送达您的账户，详情见“我的奖励”。'
            );
            SMSService::instance()->RegisterSMS('618','6666','1',$paramObj->mobile);
            //邀请人
            if (!empty($paramObj->invite_code)) {
                $invite_id = $this->mUser->CheckInviteId($paramObj->invite_code);
                if ($invite_id) {
                    DB::table('user')->where('user_id', $user_id)->update(array('parent_id' => $invite_id->user_id));
                    DB::table('invite')->insert(array(
                        array('user_id' => $user_id, 'invite_id' => $invite_id->user_id, 'add_time' => time()),
                    ));
                }
            }

            $data = $this->mUser->UserFirphone($paramObj->mobile);
            #存储SESSION
//            Session_put(UserEnum::USER_INFO_USER_ID, $user_id);
//            Session_put(UserEnum::USER_INFO_SESSION_KEY, $data);
            $_SESSION[UserEnum::USER_INFO_SESSION_KEY] = $data;
            $_SESSION[UserEnum::USER_INFO_USER_ID] = $data->user_id;
            return $data;
        } else {
            throw new Exception('注册失败');
        }

    }


    /**
     * 获取个人资金信息
     * @return array
     * @throws Exception
     * @author fyl
     * @data  2016-12-23
     */
    public function ApiUserAccounts()
    {
        #验证登录
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        $user_id = $_SESSION[UserEnum::USER_INFO_USER_ID];
        #验证登录
        //$user_data = $_SESSION[UserEnum::USER_INFO_SESSION_KEY];
        #返回数据
        // 获取个人资产
        $fund = UserService::instance()->GetFund($user_id);
        // 已激活红包金额
        $awardAmount = $this->mUserAward->AwardAmount($user_id);
        // 已激活加息券
        $ticketInfo = $this->mUserTicket->TicketAmount($user_id);
        //加息劵金额
        $ticketAmount = 0;
        if(!empty($ticketInfo)){
            foreach($ticketInfo as $v) {
                $ticketAmount += $v->rate * $v->amount;
            }
        }
        // 代收本息
        // 回款计划
        $refundPlan = $this->mRefundPlan->RefundPlan($user_id);

        // 等待回款本金
        $waitRefundCapital = 0;
        // 等待回款利息
        $waitRefundAccrual = 0;
        // 已回款利息
        $refundAccrual = 0;
        // 待回款总金额
        $waitRefundTotalAmount = 0;
        // 已回款总金额
        $refundTotalAmount = 0;
        // 等待回款计划
        $waitRefundPlan    = [];
        //体验标
        $TiyanItem = $this->mExperRecord->MonthTiyan($user_id);
        //体验金盈利
        if ($TiyanItem) {
            $TiyanItem = $TiyanItem->return_money;
        } else {
            $TiyanItem = '0';
        }
        $today = strtotime(date('Y-m-d', time()));
        $accrual = 0;
        foreach ($refundPlan as $key => &$value) {
            $value->totalAmount = $value->amount_capital + $value->amount_accrual;
            $value->refund_time_text = date('Y-m-d', $value->refund_time);
            if ($value->status == 0) {
                $waitRefundCapital += $value->amount_capital;
                $waitRefundAccrual += $value->amount_accrual;
                $waitRefundTotalAmount += $value->totalAmount;
            } else {
                $refundTotalAmount += $value->totalAmount;
                $refundAccrual += $value->amount_accrual;
            }

            if($value->refund_time>$today){
                //每天利息
                $day_accrual = $value->amount_accrual/$value->deadline;
                $cha_day = ceil(($today-$value->start_time)/86400);
                $accrual += $day_accrual*$cha_day;
            }
            //dd($oldday,$value->start_time,$today);
        }
        unset($value);

        $myFund = [
            // 可用余额
            'money'         => number_format($fund->money / 100, 2),
            //截止昨日盈利
            'totalAccrual'       => number_format(($refundAccrual + $awardAmount + $TiyanItem +$accrual + $ticketAmount) / 100, 2),
            //总资产
            'totalMoney'    =>number_format(($fund->money + $waitRefundCapital + $waitRefundAccrual + $fund->money_freeze + $ticketAmount) / 100, 2),
            // 待收本金
            'capital'       => number_format($waitRefundCapital / 100, 2),
            // 待收利息
            'accrual'   => number_format($waitRefundAccrual / 100, 2),
            // 冻结金额
            'money_freeze' => number_format($fund->money_freeze / 100, 2),
        ];

        return $myFund;

    }

    /**
     * 我的红包信息
     * @return array
     * @throws Exception
     * @author xf
     * @data  2016-12-26
     */
    public function UserAccountsMyred($page)
    {
        if(empty($page)){
            $page=1;
        }

        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        $user_id=$_SESSION[UserEnum::USER_INFO_USER_ID];
        $data = $this->mUserAward->APIUserAward($user_id, $page);
        foreach ($data as $v) {
            $v->limitse = '仅限于≥' . $v->limit . '天投资项目';
            $v->amount= $v->amount/100;
            $v->restrict_amount= $v->restrict_amount/100;
        }

        $array=array();
        foreach($data as $v){
            if($v->status=='AVAILABLE'||$v->status=='ACTIVATE'){
                $array[] = $v;
            }
        }
        foreach($data as $v){
            if($v->status=='HAS_USED'||$v->status=='PAST_DUE'){
                $array[] = $v;
            }
        }

        return $array;
    }

    /**
     * 忘记密码
     * @return array
     * @throws Exception
     * @author xf
     * @data  2016-12-27
     */
    public function ForgetPwd($paramObj)
    {
        if (empty($paramObj->phone) || empty($paramObj->newpwd) || empty($paramObj->surepwd)) {
            throw new Exception("参数不足", ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        if (!preg_match("/^1[34578]{1}\d{9}$/", $paramObj->phone)) {
            ;
            throw new Exception('请输入正确的手机号！', ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }
        //php是否存在
        $data = $this->mUser->UserFirphone($paramObj->phone);
        if (empty($data)) {
            throw new Exception('不存在的用户！', ProfessionErrorCodeEnum::ERROR_ACCOUNT_NOT_EXIST);
        }
        if (!preg_match("/(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,16}$/", $paramObj->newpwd)) {
            throw new Exception("6-16个字符，由字母+数字和符号两种以上组合", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }
        if ($paramObj->newpwd != $paramObj->surepwd) {
            throw new Exception('对不起，两次输入密码不一致！', ProfessionErrorCodeEnum::ERROR_PASSWORD_DIFFERENT);
        }
        //新的密码加密
        $salt = rand(100000, 999999);
        $newpsswd = UserEnum::get(md5(md5($paramObj->newpwd)), $salt);//加密方式
        $pwddata = array(
            'password' => $newpsswd,
            'salt' => $salt,
        );
        $deta = $this->mUser->update($pwddata, ['user_id' => $data->user_id]);
        if(empty($deta)){
            throw new Exception('修改密码失败！', ProfessionErrorCodeEnum::ERROR_PASSWORD_SET_FAIL);

        }
        return new stdClass();


    }

    /**
     * 手机号是否存在
     * @return array
     * @throws Exception
     * @author xf
     * @data  2016-12-27
     */
    public function NumPhone($paramObj)
    {
        //php判断是否为空
        if (!preg_match("/^1[34578]{1}\d{9}$/", $paramObj->phone)) {
            throw new Exception('请输入正确的手机号！', ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }
        //php是否存在
        $data = $this->mUser->UserFirphone($paramObj->phone);
        if(empty($data)){
            $da=0;
        }else{
            $da=1;
        }
        $date=new stdClass();
        $date->phmo=$da;
        return $date;


    }

    /**
     * 获取个人中心信息
     * @return array
     * @throws Exception
     * @author xf
     * @data  2016-12-27
     */
    public function UserInformition()
    {
        //UserEnum::USER_INFO_USER_ID
        //$user_id=session_get(UserEnum::USER_INFO_USER_ID);
//        print_r($user_id);
//        die;USER_INFO_SESSION_KEY
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        $user_id = $_SESSION[UserEnum::USER_INFO_USER_ID];

//        if (empty($user_id)) {
//            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
//        }
        return $this->mUser->UserInfofirst($user_id);


    }


    /**
     * 修改个人中心密码
     * @return array
     * @throws Exception
     * @author xf
     * @data  2016-12-27
     */
    public function UpdatePwd($paramObj)
    {
        if (empty($paramObj->oldpwd) || empty($paramObj->newpwd)) {
            throw new Exception("参数不足", ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        $user_id=$_SESSION[UserEnum::USER_INFO_USER_ID];
        if (empty($user_id)) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        $user_data=$this->mUser->UserInfo($user_id);
        $psswd = UserEnum::get(md5(md5($paramObj->oldpwd)), $user_data->salt);//加密方式

        if ($psswd != $user_data->password) {
            throw new Exception('原密码错误！', ProfessionErrorCodeEnum::ERROR_PASSWORD_ORIGINAL_WRONG);
        }
        if (!preg_match("/(?!^[0-9]+$)(?!^[A-z]+$)(?!^[^A-z0-9]+$)^.{6,16}$/", $paramObj->newpwd)) {
            throw new Exception("6-16个字符，由字母+数字和符号两种以上组合", ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }
        //新的密码加密
        $salt = rand(100000, 999999);
        $newpsswd = UserEnum::get(md5(md5($paramObj->newpwd)), $salt);//加密方式
        $pwddata = array(
            'password' => $newpsswd,
            'salt' => $salt,
        );
        $deta = $this->mUser->update($pwddata, ['user_id' => $user_data->user_id]);
        if(empty($deta)){
            throw new Exception('重置密码失败！', ProfessionErrorCodeEnum::ERROR_PASSWORD_RESET_FAIL);

        }
        return new stdClass();


    }


    /**
     * 我的加息券
     * @param $page
     * @return mixed
     * @throws Exception
     */
    public function UserTicket($page)
    {

//        $user_id=session_get(UserEnum::USER_INFO_USER_ID);
//        if (empty($user_id)) {
//            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
//        }
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        $user_id = $_SESSION[UserEnum::USER_INFO_USER_ID];
        if (empty($page)) {
            $page == 1;
        }
        $data =  $this->mUserTicket->UserTicket($user_id,$page);
        foreach($data as $k=>$v){
            $data[$k]->rate = $v->rate/100;
            foreach(ItemEnum::$Item_types as $kk=>$vv){
                if($v->restrict_item==$kk){
                    $data[$k]->restrict_item = '适用'.$vv.'投资项目';
                }
            }
        }

        return $data;

    }


    /**
     *我的消息
     **/
    public function ApiOwnmesgcount()
    {
        $user_id=$_SESSION[UserEnum::USER_INFO_USER_ID];
        return $this->mUserMessage->Ownmesgcount($user_id);
    }


    /**
     * 实名认证
     * @param $page
     * @return mixed
     * @throws Exception
     */
    public function AuthUserName($paramObj)
    {
        if (empty($paramObj->name) || empty($paramObj->idcard) || empty($paramObj->banck) || empty($paramObj->phone)) {
            throw new Exception("参数不足", ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        $user_id=$_SESSION[UserEnum::USER_INFO_USER_ID];
        $user_data = $_SESSION[UserEnum::USER_INFO_SESSION_KEY];
        //银行卡判断
        if (!preg_match(" /^(\d{16}|\d{19})$/", $paramObj->banck)) {
            throw new Exception('银行卡号格式不对！', ProfessionErrorCodeEnum::ERROR_BANCKCARD_GESHI_SUCCESS);
        }
        if (!preg_match("/^1[34578]{1}\d{9}$/", $paramObj->phone)) {
            throw new Exception('请输入正确的手机号！', ProfessionErrorCodeEnum::ERROR_USER_MOBILE_FAILURE);
        }
        if (!preg_match("/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/", $paramObj->idcard)) {
            throw new Exception('身份证格式不对！', ProfessionErrorCodeEnum::ERROR_IDCARD_GESHI_SUCCESS);
        }

        $bankshifou= $this->mBankCard->GetUserBankCard($user_id);

        #开始事务
        DB::beginTransaction();
        try {
            $banck = array(
                'telephone' => $paramObj->phone,
                'bank_num' => $paramObj->banck,
                'is_valid' => 1,
                'bank_code' => 'ICBC',
                'add_time' => time(),
                'user_id' => $user_data->user_id
            );
            if(empty($bankshifou)){
                $this->mBankCard->insert($banck);
            }else{
                $this->mBankCard->update($banck, ['user_id' =>$user_id]);
            }

            $userdata = array(
                'name' => $paramObj->name,
                'idcard' => $paramObj->idcard,
                'is_idcard' => 1,
            );
            $this->mUser->update($userdata, ['user_id' => $user_data->user_id]);
            #结束事务
            DB::commit();
            return new stdClass();
        } catch (Exception $e) {
            #事务回滚
            DB::rollback();
            throw $e;
        }

    }

    //-------------------------------------------充值--------------------------------------------


    public function UserDepositRecharge($amount){

        // 检查充值条件
        $result = $this->_checkDeposit($amount);
        // 错误跳转地址
        $redirect = url('/user/deposit/index');

        if ($result != 200)
        {
            throw new Exception("$result", 400);
        }

        // 构建支付表单
        $result = $this->buildTrade(
        // 用户ID
            $_SESSION[UserEnum::USER_INFO_USER_ID],
            // 支付金额
            $amount,
            // 业务说明
            'USER',
            // 是否移动端
            0,
            // 是否使用存管通支付接口
            false
        );

        // 构建失败
        if ($result != 200)
        {
            throw new Exception("$result", 400);
        }

        return $amount/100;
    }


    /**
     * 支付成功
     */
    public function success($tradeNum)
    {

        // 查询出充值订单
        $trade = DB::table('deal_deposit')
            ->select('auto_id','trade_num','user_id','detail','amount','status')
            ->where('trade_num',$tradeNum)
            ->where('status','WAIT')
            ->first();

        if (!$trade)
        {
            return '支付订单不存在';
        }

        // 资金操作

        $result = DealService::instance()->carry(
        // 用户ID
            $trade->user_id,
            // 总资金
            $trade->amount,
            // 事件ID
            $trade->auto_id,
            // 交易类型
            'IN_DEPOSIT',
            // 交易资金明细
            ['MONEY_DEPOSIT' => $trade->amount],
            // 业务说明
            'DEPOSIT'
        );
        // 发送站内消息
        if ($result == 200)
        {
            // 更新订单状态
            $depositWhere  = [
                'auto_id' => $trade->auto_id,
                'status'  => 'WAIT',
            ];
            $updateDeposit = [
                'status'      => 'SUCCESS',
                'finish_time' => time(),
            ];

            $trade1 = DB::table('deal_deposit')->where($depositWhere)->update($updateDeposit);

            UserService::instance()->send(
            // 接收者ID
                $trade->user_id,
                // 标题
                '充值成功',
                // 内容
                '尊敬的用户，您已成功充值'.number_format($trade->amount/100, 2).' 元，详情请到账户概况查看。'
            );
        }


        return $result;
    }



    /**
     * @param $amount
     * @return mixed
     * 充值判断
     */
    public function _checkDeposit($amount)
    {
        // 检查用户身份证是否认证
        $user_id = $_SESSION[UserEnum::USER_INFO_USER_ID];
        //用户是否登录
        $user_info = $this->mUser->GetUserInfo($user_id);

        // 检查用户身份证是否认证
        if (!$user_info->is_idcard)
        {
            throw new Exception("为保证投资安全，请先完成实名认证", 400);
        }
        // 充值条件
        $condition = UserEnum::condition();

        // 检查充值金额
        if ($amount < $condition['min_amount'])
        {
            throw new Exception('每笔充值金额不少于2元', 400);
        }

//        if ($amount%100 != 0)
//        {
//            throw new Exception("每笔充值金额不能含有分、角, 您输入的投资金额是".number_format($amount/100, 2)."元", 400);
//        }

        if ($amount >= 1000000000)
        {
            throw new Exception('每笔充值金额不能超过 10,000,000 元', 400);
        }

        // 检查充值条件
        $check = UserEnum::check();

        if ($check['status'] != 200)
        {
            throw new Exception('服务器处理错误', 400);
        }

        return 200;
    }

    /**
     * @param $userid
     * @param $amount
     * @param $detail
     * @param bool $isMobile
     * @param bool $isLazycat
     * @return mixed
     * 充值
     */
    public function buildTrade($userid, $amount, $detail, $isMobile = false, $isLazycat = true)
    {

        if (!array_key_exists($detail, StatusEnum::detail()))
        {
            throw new Exception("业务类型错误, 请稍后再试", 400);
        }

        $depositParams = [
            'detail' => '钢票网账户充值',
        ];

        // 固定富友支付
        $payType = 'FUIOU';

        // 移动端使用快捷支付, 否则为网关支付

        if ($isMobile)
        {
            $payWay   = 'SWIFT';
            $bankcard = $this->mBankCard->GetUserBankCard($userid);
            if (!$bankcard)
            {
                return '您的账户还未绑定银行卡';
            }
            $depositParams['bank_code'] = $bankcard->bank_code;
        }
        else
        {

            $payWay  = 'WEB';
        }

        // 创建订单号
        $tradeNum = StatusEnum::buildNumber('DEPOSIT');

        if (!$tradeNum)
        {
            return '订单号创建失败，请稍后再试';
        }
        $bankcard['auto_id'] = '';
        // 构建一张支付订单
        $trade = [
            // 订单号码
            'trade_num'=> $tradeNum,
            // 用户ID
            'user_id'  => $userid,
            // 银行卡ID
            //'bank_id'  => $bankcard['auto_id']?$bankcard['auto_id']:'',
            // 订单金额, 分为单位
            'amount'   => $amount,
            // 支付平台
            'pay_type' => $payType,
            // 支付方式
            'pay_way'  => $payWay,
            // 交易发起端
            'device'   => 'pc',
            // 业务类型
            'detail'   => $detail,
            // 订单状态
            'status'   => 'WAIT',
            // 创建时间
            'add_time' => time(),
        ];


        // 保存订单数据
        $tradeID =  DB::table('deal_deposit')->insertGetId($trade);

        if (!$tradeID)
        {
            return  '订单创建失败, 请稍后再试';
        }

        $trade['auto_id']  = $tradeID;

        //成功
        $fund_s = $this->success($tradeNum);
//        if ($isLazycat)
//        {
//            $payMilleware = \moon\middleware("payment\\Lazycat");
//        }
//        else
//        {
//            // 支付平台
//            $payType = ucfirst(strtolower($payType));
//            $payMilleware = \moon\middleware("payment\\{$payType}");
//        }

//        // 是否移动端
//        $payMilleware->isMobile = $isMobile;
//        // 设置订单
//        $payMilleware->trade    = $trade;
//        // 设置参数
//        $payMilleware->params   = $depositParams;
//
//        // 构建支付
//        $paydata = $payMilleware->build();

        if($fund_s!=200){
            return "$fund_s";
        }
        return 200;
    }

    public function AddUserFund($amount){

        $status = DB::table('user_fund')->increment('money_deposit',$amount);
        return 200;
    }


    //---------------------------------------------提现--------------------------------------------

    /**
     * @param $amount
     * @return mixed
     * 提现验证
     */
    public function _checkCash($amount)
    {
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }

        $user_id = $_SESSION[UserEnum::USER_INFO_USER_ID];
        //用户是否登录
        $user_info = $this->mUser->GetUserInfo($user_id);

        $user_bankcard = $this->mBankCard->GetUserBankCard($user_info->user_id);
        // 检查用户身份证是否认证
        if (!$user_info->is_idcard)
        {
            throw new Exception("为保证投资安全，请先完成实名认证", 400);
        }

        // 检查银行卡
//        if (empty($user_bankcard))
//        {
//            throw new Exception("您的账户还未绑定银行卡，无法进行提现", 400);
//        }

        // 检查金额格式
        if ($amount <= 0)
        {
            throw new Exception('提现金额必须大于0元，您输入的是 '.$amount.' 元', 400);
        }

        // 检查提现条件
        $check = UserEnum::CashCheck();

        if ($check['status'] != 200)
        {
            throw new Exception('400', 400);
        }

        $cashFee = $this->getFee($_SESSION[UserEnum::USER_INFO_USER_ID], $amount);
        $fee     = $cashFee['totalFee_unit']?$cashFee['totalFee_unit']*100:0;
        if ($amount <= $fee)
        {
            throw new Exception('提现金额小于提现所需手续费，无法进行提现，提现所需手续费为：'.number_format($fee/100,2).' 元', 400);
        }

        $data = $cashFee?$cashFee:'';
        return ['status'=>200,'data'=>$data];
    }

    /**
     * @param $amount
     * 提现
     */
    public function UserCashRecharge($amount){
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        $user_id = $_SESSION[UserEnum::USER_INFO_USER_ID];
        // 检查提现条件
        $cashFee  = $this->_checkCash($amount);

        // 错误跳转地址
        $redirect = url('/user/cash/index');

        if ($cashFee['status'] != 200)
        {
            throw new Exception('提现操作错误', 400);
        }
        $feeDetail = $cashFee['data'];

        //$bankcard  = $this->GetUserBankCard($user_id);
        // 创建订单号
        $tradeNum = StatusEnum::buildNumber('CASH');

        if (!$tradeNum)
        {
            throw new Exception('订单号创建失败，请稍后再试',400);
        }
        // 创建提现订单
        $tableVal = [
            // 订单号码
            'trade_num'    => $tradeNum,
            //用户ID
            'user_id'      => $user_id,
            // 提现总金额
            'amount'       =>$amount,
            // 提现手续费
            'fee'        =>$feeDetail['totalFee_unit']*100,
            // 手续费详情
            'fee_detail'    =>json_encode(['liveFee' => $feeDetail['liveFee_unit']*100, 'depositFee' => $feeDetail['depositFee_unit']*100]),
            // 银行卡ID
            'bankcard_id'   =>110110110110110110,
            // 设备
            'device'     =>'MOBILE',
            //状态
            'status'    => 'WAIT',
            // 添加时间
            'add_time'  => time(),
        ];

        $trade = DB::table('deal_cash')->insert($tableVal);

        // 订单创建失败
        if (!$trade)
        {
            throw new Exception('提现操作错误', 400);
        }
        $fund_s = $this->confirm($tradeNum);

        if($fund_s!=200){
            throw new Exception('$fund_s', 400);
        }
        return 200;
//       // 构建支付表单
//       $dealLazy = \moon\middleware('lazycat\\Deal');
//
//       $result = $dealLazy->withdraw(
//       // 订单号码
//           $trade['data']['trade_num'],
//           // 客户端
//           $this->request->isMobile()?'MOBILE':'PC',
//           // 用户ID
//           $this->_user['user_id'],
//           // 支付金额
//           $amount/100,
//           $feeDetail['totalFee']/100
//       );
//
//       // 构建失败
//       if ($result['status'] != 200)
//       {
//           return $this->error(400, $result['info'], $redirect);
//       }
//
//       list($url, $data) = $result['data'];
//
//       $tpldata = [
//           // 提交URL
//           'url'  => $url,
//           // 表单数据
//           'data' => $data,
//       ];
    }

    /**
     * @param $amount
     * @param $userid
     * 计算提现手续费
     */
    public function getFee($userid, $amount)
    {
        $fund = UserService::instance()->GetFund($userid);
        // 检查余额
        if ($fund->money < $amount)
        {
            throw new Exception("余额不足，当前可用余额为 $fund->money_format 元", 400);
        }
        // 提现手续费配置
        $cashFactor = UserEnum::fee_factor();

        // 回款金额
        $liveAmount = $fund->money - $fund->money_deposit;

        // 回款及福利金额手续费
        $liveFee    = 0;
        // 充值未投资手续费
        $depositFee = 0;

        // 回款及福利金额最小手续费
        $minLiveFee = $cashFactor['money_live_fee_min']*100;
        // 充值未投资最小提现手续费
        $minDepositFee = $cashFactor['money_deposit_fee_min']*100;

        if ($amount <= $liveAmount)
        {
            // 实际回款提现金额
            $liveCashAmount = $amount;
            // 计算手续费
            $liveFee = ceil($liveCashAmount * $cashFactor['money_live_fee']);
            $liveFee = ($liveFee < $minLiveFee) ? $minLiveFee : $liveFee;
        }
        else
        {
            // 如果提取回款金额
            if ($liveAmount != 0)
            {
                $liveFee = $minLiveFee;
            }

            $depositCashAmount = $amount - $liveAmount;

            $depositFee = ceil($depositCashAmount * $cashFactor['money_deposit_fee']);
            $depositFee = ($depositFee < $minDepositFee) ? $minDepositFee : $depositFee;
        }

        // 每月两次免费机会
//        $isMonthFree = false;
//        if ($liveFee > 0)
//        {
//            $monthStartTime = strtotime(date('Y-m-').'1');
////            $cashWhere = [
////                'add_time' => ['>', $monthStartTime],
////                'user_id'  => $userid,
////                'status'   => ['<>', 'WAIT'],
////            ];
//            $thisMonthCount = DB::table('deal_cash')
//                ->where('user_id',$userid)
//                ->where('add_time','>',$monthStartTime)
//                ->whereIn('status','!=','WAIT')
//                ->count();
//
//            if ($cashFactor['month_free_count'] > $thisMonthCount)
//            {
//                $liveFee = 0;
//                $isMonthFree = true;
//            }
//        }

        // 预计到账金额
        $amountPlan = ($amount-$liveFee-$depositFee) > 0 ?($amount-$liveFee-$depositFee):0;

        $fee = [
//            // 提现总金额
//            'amount'     => $amount,
//            // 回款及福利金额提现手续费
//            'liveFee'    => $liveFee,
//            // 充值未投资提现手续费
//            'depositFee' => $depositFee,
//            // 总手续费
//            'totalFee'   => $liveFee+$depositFee,
//            // 预计到账金额
//            'amountPlan' => $amountPlan,
//            // 月免费提现
//            //'is_month_free'   => $isMonthFree,
            // 单位转为元
            'liveFee_unit'    => number_format($liveFee/100,2),
            'depositFee_unit' => number_format($depositFee/100,2),
            'totalFee_unit'   => number_format(($liveFee+$depositFee)/100,2),
            'amountPlan_unit' => number_format($amountPlan/100,2),
        ];
        return  $fee;
    }

    /**
     * 提现确认操作
     * 提现金额操作至冻结金额
     */
    public function confirm($tradeNum)
    {
        // 查询出提现订单
        // 查询出充值订单
        $trade = DB::table('deal_cash')
            ->select('auto_id','trade_num','user_id','amount','status')
            ->where('trade_num',$tradeNum)
            ->where('status','WAIT')
            ->first();

        // 存在订单 修改提现订单状态
        if (!$trade)
        {
            return  '提现订单不存在[确认提现]';
        }

        // 计算提现金额明细
        $fund   = UserService::instance()->GetFund($trade->user_id);

        $amount = $trade->amount;
        // 使用的回款金额
        $returnAmount  = 0;
        // 使用的福利金额
        $awardAmount   = 0;
        // 使用的充值未投资金额
        $depositAmount = 0;

        // 首先使用回款金额
        if ($amount < $fund->money_return)
        {
            $returnAmount = $amount;
            $amount       = 0;
        }
        else
        {
            $returnAmount = $fund->money_return;
            $amount       = $amount - $returnAmount;
        }

        // 是否使用福利金额
        if ($amount > 0)
        {
            if ($amount < $fund->money_award)
            {
                $awardAmount = $amount;
                $amount      = 0;
            }
            else
            {
                $awardAmount = $fund->money_award;
                $amount      = $amount - $awardAmount;
            }
        }

        // 是否使用充值未投资金额
        if ($amount > 0)
        {
            if ($amount < $fund->money_deposit)
            {
                $depositAmount = $amount;
                $amount        = 0;
            }
            else
            {
                $depositAmount = $fund->money_deposit;
                $amount        = $amount - $depositAmount;
            }
        }

        // 资金操作明细
        $cashDetail    = ['MONEY_FREEZE' => $trade->amount];
        $returnAmount  && $cashDetail['MONEY_RETURN']  = -$returnAmount;
        $awardAmount   && $cashDetail['MONEY_AWARD']   = -$awardAmount;
        $depositAmount && $cashDetail['MONEY_DEPOSIT'] = -$depositAmount;
        $trade1 = DB::table('deal_cash')->where('auto_id',$trade->auto_id)->update(['status'=>'SUCCESS']);
        $result = DealService::instance()->carry(
        // 用户ID
            $trade->user_id,
            // 总资金
            -$trade->amount,
            // 事件ID
            $trade->auto_id,
            // 交易类型
            'DE_CASH',
            // 交易资金明细
            $cashDetail,
            // 业务说明
            'CASH'
        );

        // 更新为待确认状态
        UserService::instance()->send(
        // 接收者ID
            $trade->user_id,
            // 标题
            '提现成功',
            // 内容
            '尊敬的用户，您于'.date('Y-m-d',time()).'申请的'.($trade->amount/100).'元提现已提交成功，将在T+1日到账，请注意查收'
        );

        return $result;
    }


    /**
     * 计算提现手续费
     */
    public function GetCashFee($amount){
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        $user_id = $_SESSION[UserEnum::USER_INFO_USER_ID];
        // 检查金额格式
        if ($amount <= 0)
        {
            throw new Exception('提现金额必须大于0元，您输入的是 '.$amount.' 元', 400);
        }
        $CashFee = $this->getFee($user_id, $amount);
        return $CashFee;
    }



    /**
     * 用户邀请码
     * @return mixed
     */
    public function UserInfoInvite($user_id)
    {
        $code =$this->mUser->UserInfoInvite($user_id);
        if(empty($code->invite_code)){
            $invite_code = 0;
        }else{
            $invite_code = $code->invite_code;
        }
        return $invite_code;
    }

    /**
     * 用户邀请已投资人数
     * @return mixed
     */
    public function InvestInviteCount($user_id)
    {
        //获取期
        $phase = InviteFriendsEnum::Phase();
        $Last_phase = count($phase)-1;
        $time = [
            $phase[$Last_phase]['start_time'],
            $phase[$Last_phase]['end_time']
        ];
        //获取被邀请人ID
        $InviteId = $this->mUser->UserInviteId($user_id,$time);
        $count = 0;
        if(!empty($InviteId)) {
            //获取被邀请人ID
            foreach ($InviteId as $v) {
                $userid[] = $v->user_id;
            }
            //获取被邀请人已投资人数
            $count = $this->mInvest->UserInvestCount($userid,$time);
        }
        return $count;
    }
    /**
     *我的消息
     **/
    public function UserAccountsOwnmesg($paramObj){
        if(empty($paramObj->page)){
            $paramObj->page=1;
        }
        if (empty($paramObj->type)) {
            throw new Exception("参数不足", ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        //消息
        if($paramObj->type=='message'){
            $user_id=$_SESSION[UserEnum::USER_INFO_USER_ID];
            if (empty($user_id)) {
                throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
            }
            return $this->mUserMessage->ApiOwnmesg($user_id,$paramObj->page);
        }
        //公告
        if($paramObj->type=='news'){
            return $this->mNew->ApiNewsId($paramObj->page);
        }
    }

    /**
     * 邀请好友查询
     * @param $user_id
     * @return mixed
     */
    public function ApiUserInvite($user_id,$page,$page_size)
    {
        //获取期
        $phase = InviteFriendsEnum::Phase();
        $Last_phase = count($phase)-1;
        $time = [
            $phase[$Last_phase]['start_time'],
            $phase[$Last_phase]['end_time']
        ];
        //获取被邀请人信息
        $info = $this->mUser->ApiUserInvite($user_id,$page,$page_size,$time);
        if(!empty($info)){
            //获取被邀请人ID
            foreach($info as $v){
                $userid[]=$v->user_id;
            }
            //获取邀请人投资记录
            $Invest_id = $this->mInvest->GetInviteInvest($userid,$time);
            //获取投资记录ID
            if(!empty($Invest_id)){
                foreach($Invest_id as $v){
                    $Investid[] = $v->user_id;
                }
                foreach($info as $v){
//                    $sub_name = substr($v->user_name,3,6);
//                    $v->user_name = str_replace($sub_name,"****",$v->user_name);
                    if(in_array($v->user_id,$Investid)){
                        $v->status = '1';
                    }else{
                        $v->status = '0';
                    }
                }
            }else{
                foreach($info as $v){
                    $v->status = '0';
                }
            }
        }
        //判断被邀请人投资状态
        return $info;
    }


    /**
     *我的消息修改状态
     **/
    public function ApiUpMessagedata($paramObj){
        if (empty($paramObj->auto_id)) {
            throw new Exception("参数不足", ProfessionErrorCodeEnum::STATUS_ERROR_PARAMS_MUST);
        }
        //消息

            if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
                throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
            }
        $user_id=$_SESSION[UserEnum::USER_INFO_USER_ID];
        $data = array(
            'is_read'=>1
        );
            $data= $this->mUserMessage->update($data,['user_id'=>$user_id,'auto_id'=>$paramObj->auto_id]);
        return new stdClass();

    }
    /**
     *银行卡的消息
     **/
    public function BankCard(){
        $user_id=$_SESSION[UserEnum::USER_INFO_USER_ID];
        $data=  $this->mBankCard->GetUserBankCard($user_id);
        if (!empty($data)) {

            $data->bank_logo='https://'.$_SERVER['HTTP_HOST'].$data->bank_logo;

            return $data;
        } else {
            $date= new stdClass();
            $date->auto_id='';
            $date->bank_code='';
            $date->bank_num='';
            $date->bank_name='';
            $date->is_valid='';
            $date->bank_logo='';
            return $date;
        }
    }


    /**
     *累计收益
     */
    public function ApiCumulativeProfit(){
        #验证登录
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            throw new Exception('用户未登录！', ErrorCodeEnum::STATUS_ERROR_NOT_LOGIN);
        }
        //$user_data = $_SESSION[UserEnum::USER_INFO_SESSION_KEY];


        $user_id = $_SESSION[UserEnum::USER_INFO_USER_ID];
        #返回数据

        // 已激活红包金额
        $awardAmount = $this->mUserAward->AwardAmount($user_id);
        // 已激活加息券
        $ticketInfo = $this->mUserTicket->TicketAmount($user_id);
        //加息劵金额
        $ticketAmount = 0;
        if(!empty($ticketInfo)){
            foreach($ticketInfo as $v) {
                $ticketAmount += $v->rate * $v->amount;
            }
        }
        // 代收本息
        // 回款计划
        $refundPlan = $this->mRefundPlan->RefundPlan($user_id);

        // 等待回款本金
        $waitRefundCapital = 0;
        // 等待回款利息
        $waitRefundAccrual = 0;
        // 已回款利息
        $refundAccrual = 0;
        // 待回款总金额
        $waitRefundTotalAmount = 0;
        // 已回款总金额
        $refundTotalAmount = 0;
        // 等待回款计划
        $waitRefundPlan    = [];
        //体验标
        $TiyanItem = $this->mExperRecord->MonthTiyan($user_id);
        //体验金盈利
        if ($TiyanItem) {
            $TiyanItem = $TiyanItem->return_money;
        } else {
            $TiyanItem = '0';
        }
        $today = strtotime(date('Y-m-d', time()));
        $accrual = 0;
        foreach ($refundPlan as $key => &$value) {
            $value->totalAmount = $value->amount_capital + $value->amount_accrual;
            $value->refund_time_text = date('Y-m-d', $value->refund_time);
            if ($value->status == 0) {
                $waitRefundCapital += $value->amount_capital;
                $waitRefundAccrual += $value->amount_accrual;
                $waitRefundTotalAmount += $value->totalAmount;
            } else {
                $refundTotalAmount += $value->totalAmount;
                $refundAccrual += $value->amount_accrual;
            }

            if($value->refund_time>$today){
              //每天利息
                $day_accrual = $value->amount_accrual/$value->deadline;
                $cha_day = ceil(($today-$value->start_time)/86400);
                $accrual += $day_accrual*$cha_day;
            }
            //dd($oldday,$value->start_time,$today);
        }
        unset($value);

        $accrual_info = $this->mAccrualDay->AccrualInfo($user_id);
        foreach($accrual_info as $k=>&$v){
            $v->accrual = number_format($v->accrual/100,2);
        }
        $myFund = [
            // 累计收益 = 累计已收利息 + 已激活红包 + 代收利息 + 加息券
            'totalAccrual' => number_format(($refundAccrual + $awardAmount + $TiyanItem +$waitRefundAccrual + $ticketAmount) / 100, 2),
            'accrual'      => number_format(($refundAccrual + $awardAmount + $TiyanItem +$accrual + $ticketAmount) / 100, 2),
            'accrual_info' => $accrual_info
        ];

        return $myFund;
    }


    /**
     *添加累计收益
     */
    public function AddAccrual(){
        ini_set('max_execution_time', '0');
        $user_all_id = $this->mUser->GetUserIdAll();
        foreach($user_all_id as $v){
            // 回款计划
            $refundPlan = $this->mRefundPlan->RefundPlan($v->user_id);
            // 等待回款本金
            $waitRefundCapital = 0;
            // 等待回款利息
            $waitRefundAccrual = 0;
            // 已回款利息
            $refundAccrual = 0;
            // 待回款总金额
            $waitRefundTotalAmount = 0;
            // 已回款总金额
            $refundTotalAmount = 0;

            $today = strtotime(date('Y-m-d', time()));
            $day_accrual = 0;
            foreach ($refundPlan as $key => &$value) {
                if($value->refund_time>$today){
                    //每天利息
                    $day_accrual += $value->amount_accrual/$value->deadline;
                }
                //dd($oldday,$value->start_time,$today);
            }
            unset($value);
            $arr = [
                'user_id'=>$v->user_id,
                'time' => time(),
                'accrual'=> number_format($day_accrual,2)
            ];
            $accrual_info[] = $arr;
           // $accrual_info = $this->mAccrualDay->insert($arr);
        }
        $bb = array_chunk($accrual_info,100);
        foreach($bb as $v){
            DB::table('accrual_day')->insert($v);
        }

    }

    /**
     * 获取App信息
     * @author  lzhp
     * @date    2016-07-08
     * @throws Exception
     */
    public function AppInitialize(){

            $app_info = $this->mVersion->GetVersion();
            $app_info->token = QiniuUpload::instance()->generateToken();
            return $data=[
                'app_info'  =>$app_info,
            ];

    }
    /**
     * 我的消息未读
     * @param $user_id
     * @return mixed
     */
    public  function MessageCount(){
        $date=new stdClass();
        if (empty($_SESSION[UserEnum::USER_INFO_USER_ID])) {
            $date->un_read=0;
            return $date;
        }
        $user_id=$_SESSION[UserEnum::USER_INFO_USER_ID];
        $data=$this->mUserMessage->MessageCount($user_id);
        $date->un_read=$data;
        return $date;

    }
}